//
//  RevanWelcomeView.swift
//  weibo_swift
//
//  Created by 紫荆秋雪 on 17/1/10.
//  Copyright © 2017年 紫荆秋雪. All rights reserved.
//

import UIKit
import SDWebImage


class RevanWelcomeView: UIView {
    /// 头像
    @IBOutlet weak var userImageView: UIImageView!
    /// 欢迎语
    @IBOutlet weak var welcomeLabel: UILabel!
    /// 头像bottom约束
    @IBOutlet weak var userImageViewBottom: NSLayoutConstraint!
    
    
    // 加载xib
    class func welcome()->RevanWelcomeView {
        let nib = UINib(nibName: "RevanWelcomeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! RevanWelcomeView
        //设置xib大小
        v.frame = UIScreen.main.bounds
        return v
    }
    
    override func awakeFromNib() {
        // 加载头像url
        guard let urlstring = RevanNetworkManager.shared.userAccount.avatar_large,
        let url = URL(string: urlstring) else {
            return
        }
        print(url)
        userImageView.sd_setImage(with: url, placeholderImage: UIImage(named: "visitordiscover_image_profile"))
        userImageView.layer.cornerRadius = userImageView.bounds.size.width * 0.5
        userImageView.layer.masksToBounds = true
    }
    
    // 显示到界面后就会调用
    override func didMoveToWindow() {
        super.didMoveToWindow()
        // 视图是使用自动布局来设置的，只是设置了约束
        // - 当视图被添加到窗口上时，根据父视图的大小，计算约束值，更新控件位置
        // - layoutIfNeeded 会直接按照当前的约束直接更新控件位置
        // - 执行之后，控件所在位置，就是 xib 中的布局位置
        self.layoutIfNeeded()
        
        // 设置头像底部约束
        userImageViewBottom.constant = bounds.size.height - 200
        
        // 动画显示
        UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { 
            // 更新约束
            self.layoutIfNeeded()
        }) { (_) in
            // 显示 欢迎归来
            UIView.animate(withDuration: 1.0, animations: { 
                self.welcomeLabel.alpha = 1.0
            }, completion: { (_) in
                self.removeFromSuperview()
            })
        }
        
    }
}
